﻿/*
	Copyright 2010 Intuitive Solutions

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	   http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/

using System;
using System.Reflection;
using Metamorph.Configuration;
using System.Collections.Generic;

namespace Metamorph.Core
{
	public class ConditionDispatcher : IConditionDispatcher
	{
		private static ConditionDispatcher cdInstance;

		public delegate bool ConditionDelegate();

		private Dictionary<string, ConditionDelegate> dConditions;

		private ConditionDispatcher()
		{
			dConditions = new Dictionary<string, ConditionDelegate>();
		}

		public Dictionary<string, ConditionDelegate> Conditions
		{
			get
			{
				return dConditions;
			}
		}

		public static ConditionDispatcher Instance
		{
			get
			{
				if (cdInstance == null)
				{
					cdInstance = new ConditionDispatcher();
				}

				return cdInstance;
			}
		}

		#region IConditionDispatcher Members

		public bool Proceed(string sConditionName, IProcessContext pcProcessContext)
		{
			bool bResult = false;
			if (sConditionName.Contains("."))
			{
				ICondition cCondition = (ICondition)AssemblyUtils.Instance.GetCodeAssembly().CreateInstance(sConditionName);

				if (cCondition == null)
				{
					throw new Exception(sConditionName + " class not found in assembly " + AssemblyUtils.Instance.GetCodeAssembly().FullName + ".");
				}

				cCondition.StateMachineContext = pcProcessContext;
				bResult = cCondition.Proceed();
			}
			else
			{
				Register(sConditionName, pcProcessContext);

				bResult = dConditions[sConditionName]();
			}

			return bResult;
		}

		#endregion

		public void Register(string sConditionName, IProcessContext pcProcessContext)
		{
			if (!dConditions.ContainsKey(sConditionName))
			{
				if (pcProcessContext == null)
				{
					throw new Exception("The process has no context associated.");
				}

				MethodInfo miMethodInfo = pcProcessContext.GetType().GetMethod(sConditionName);

				if (miMethodInfo == null)
				{
					throw new Exception(sConditionName + " Method not found in " + pcProcessContext.GetType().FullName + " class.");
				}

				ConditionDelegate cdConditionDelegate = (ConditionDelegate)Delegate.CreateDelegate(typeof(ConditionDelegate), pcProcessContext, miMethodInfo, true);
				dConditions.Add(sConditionName, cdConditionDelegate);
			}
		}
	}
}
